package com.zjsru.plan2023.oneday;

import java.util.Arrays;

/**
 * @Author: CookLee
 * @Date: 2023/5/14
 * 距离相等的条形码
 *
 * 输入：barcodes = [1,1,1,2,2,2]
 * 输出：[2,1,2,1,2,1]
 *
 * 输入：barcodes = [1,1,1,1,2,2,3,3]
 * 输出：[1,3,1,3,2,1,2,1]
 */
public class RearrangeBarcodes {
    
    /**
     * 重新安排条形码
     *
     * @param barcodes 条形码
     * @return {@link int[]}
     */
    public int[] rearrangeBarcodes(int[] barcodes) {
        int length = barcodes.length;
        Integer[] before = new Integer[length];
        int maxLength = 0;
        //统计最大数字 为下面统计出现次数提供条件
        for (int i = 0; i < length; i++) {
            before[i] = barcodes[i];
            maxLength = Math.max(maxLength, before[i]);
        }
        //获取出现数字的计数
        int[] count = new int[maxLength + 1];
        for (int num : barcodes) {
            count[num]++;
        }
        //给before数组排序，从小到大 如果相同数字则按照先后顺寻
        Arrays.sort(before, (a, b) -> count[a] == count[b] ? a - b : count[b] - count[a]);
        //指定数据长度
        int[] ans = new int[length];
        //按照奇数偶数规律开始填入数字
        for (int i = 0, j = 0; i < 2; ++i) {
            for (int k = i; k < before.length; k += 2) {
                ans[k] = before[j];
                j++;
            }
        }
        return ans;
    }
    
    public static void main(String[] args) {
        RearrangeBarcodes rearrangeBarcodes = new RearrangeBarcodes();
        int[] barcoddes = new int[]{1,1,1,2,2,2};
        System.out.println(rearrangeBarcodes.rearrangeBarcodes(barcoddes));
    }
}
